package com.open.admin.security.filter;


import com.open.system.domain.SecurityUser;
import com.open.system.entity.SysUser;
import com.open.system.utils.JwtUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("Authorization");
        log.info("\ntoken: {}", token);
        String requestURI = request.getRequestURI();
        log.info("\n访问地址: {}", requestURI);


        try {

            Long userId = JwtUtils.getUserId(token);
            log.info("\ntoken检验成功");
            log.info("\n用户id:{}", userId);

            SysUser sysUser = new SysUser();

            //用户权限列表
            List<String> permissions = new ArrayList<>();

            permissions.add("test");

            SecurityUser securityUser = new SecurityUser(sysUser, permissions, null);

            Collection<? extends GrantedAuthority> authorities = securityUser.getAuthorities();

            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(sysUser, null, authorities);
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }catch (Exception e){

        }
        filterChain.doFilter(request, response);

    }
}
